import { Config } from '../../config'

const preKey = Config.localKey

const LocalStorage = {

    set(key: string, value) {
        try {
            if (typeof value == 'object')
                value = JSON.stringify(value)
            cc.sys.localStorage.setItem(this.encrypt(preKey + key), this.encrypt(value, preKey + key))
        } catch (e) {

        }
    },

    get(key: string, defaultValue?) {
        try {
            let result = cc.sys.localStorage.getItem(this.encrypt(preKey + key));
            if (result == null) {
                return defaultValue
            }
            result = this.decrypt(result, preKey + key);
            result = this.decrypt(result, preKey + key);

            switch (typeof defaultValue) {
                case 'object': {
                    let ret = defaultValue;
                    try {
                        let parse = JSON.parse(result);
                        if (typeof parse === 'object') {
                            ret = parse;
                        }
                    } catch {

                    }
                    return ret;
                }
                case "boolean": {
                    return (result === "true")
                }
                case "number": {
                    return Number(result) || defaultValue;
                }
            }
            return result
        } catch (error) {
            return defaultValue
        }
    },

    // 加密
    encrypt(str: string, pwd: string = preKey) {
        let pwd_length = 0;
        for (let index = 0, len = pwd.length; index < len; index++) {
            pwd_length += pwd.charCodeAt(index);
        }

        str = str.toString()
        str += pwd;
        let c = String.fromCharCode(str.charCodeAt(0) + str.length * pwd_length);
        for (let i = 1; i < str.length; i++) {
            c += String.fromCharCode(str.charCodeAt(i) + str.charCodeAt(i - 1));
        }
        return encodeURIComponent(c);
    },

    // 解密
    decrypt(str: string, pwd: string = preKey) {
        let pwd_length = 0;
        for (let index = 0, len = pwd.length; index < len; index++) {
            pwd_length += pwd.charCodeAt(index);
        }
        str = str.toString()
        str = decodeURIComponent(str);
        let c = String.fromCharCode(str.charCodeAt(0) - str.length * pwd_length);
        for (let i = 1; i < str.length; i++) {
            c += String.fromCharCode(str.charCodeAt(i) - c.charCodeAt(i - 1));
        }
        return c.slice(0, c.length - pwd.length);
    }

}

export { LocalStorage }